package com.rsg.component;

import com.rsg.core.ProjectPreference;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
/*
*JButton的扩展
* 链式构建
* 代码图形
* 连续矢量绘图
* */

/**
 * RButton,以成员对象保存MakeChain,getMakeChain()方法可以获取此控件的构造链
 * @author Rock Chin
 */
public class RButton extends JButton{

	//调用此linkedMake以进行链式构造
	private MakeChain<RButton> makeChain=new MakeChain<>(this);
	private Color borderColor=Color.white;
	//超类的构造方法
	public RButton(){
		super();
		init();
	}
	public RButton(String text){
		super(text);
		init();
	}
	public RButton(Icon icon){
		super(icon);
		init();
	}
	public RButton(Action action){
		super(action);
		init();
	}
	public RButton(String text,Icon icon){
		super(text,icon);
		init();
	}

	public MakeChain<RButton> getMakeChain(){
		return makeChain;
	}


	public void init(){
		this.setBackground(ProjectPreference.component_background_color);
		this.setForeground(ProjectPreference.component_foreground_color);
	}
	//绘图方法
	@Override
	public void paint(Graphics g){
		//计算图标和文字总长，然后置于正中，图标和文字间隔3pixel

		//图标不是null则加上图标宽度和3像素
		int contextWidth=this.getIcon()==null?0:this.getIcon().getIconWidth()+3;
		//以本btn字体初始化fontmetrics
		FontMetrics fontMetrics=g.getFontMetrics(this.getFont());

		contextWidth+=fontMetrics.stringWidth(this.getText());
		//绘制起点x
		int drawIcon_x=this.getWidth()/2-contextWidth/2;
		int drawText_x=this.getIcon()==null?this.getWidth()/2-fontMetrics.stringWidth(this.getText())/2
				:drawIcon_x+this.getIcon().getIconWidth()+5;

		//分别计算icon和text的绘制起点y
		int drawIcon_y=this.getHeight()/2-(this.getIcon()==null?0:this.getIcon().getIconHeight()/2);
		int drawText_y=this.getHeight()/2+(int)(fontMetrics.getHeight()*0.26);

		//绘制background
		g.setColor(this.getBackground());
		g.fillRect(0,0,this.getWidth(),this.getHeight());

		//绘制icon和text
		g.setFont(this.getFont());
		g.setColor(this.getForeground());
		if(this.getIcon()!=null){
			this.getIcon().paintIcon(this,g,drawIcon_x,drawIcon_y);
		}
//		g.drawImage((Image) this.getIcon(),drawIcon_x,drawIcon_y,this);
		g.drawString(this.getText(),drawText_x,drawText_y);

		g.setColor(borderColor);
		g.drawRect(0,0,this.getWidth()-1,this.getHeight()-1);
	}
	@Override
	public void setBackground(Color bg){
		super.setBackground(bg);
		//System.out.println("  bg"+bg.toString());
		this.borderColor=getBrighterColor(bg,0.3f);
	}
	public Color getBrighterColor(Color cl,float rate){
		//System.out.println((int)((255-cl.getRed())*rate+cl.getRed())+" "+(int)((255-cl.getGreen())*rate+cl.getGreen())+" "+(int)((255-cl.getBlue())*rate+cl.getBlue()));
		return new Color((int)((255-cl.getRed())*rate+cl.getRed()),(int)((255-cl.getGreen())*rate+cl.getGreen()),(int)((255-cl.getBlue())*rate+cl.getBlue()));
	}
}
